// add业务模块
console.log( 'add业务模块' )

import axios from 'axios'
import './islogin.js'

let upfile_form = document.querySelector('.upfile_form')

upfile_form.onsubmit = function (e){
    // 阻止表单提交
    e.preventDefault()
    // 创建fromdata对象（获取表单数据）
    let formdata = new FormData(this)
    // 上传图片
    axios({
        method: 'post',
        url: 'http://localhost:8080/goods/upload',
        data: formdata,
        headers: {
            'Content-Type': 'multipart/form-data'
        }
    })
    .then((res)=>{
        alert(res.data.msg)
        if (res.data.code === 1) {
            document.querySelector('#imgurl').value = res.data.imgurl
        }
    })
}

let btn_primary = document.querySelector('.btn-primary')
btn_primary.onclick = function (){
    // 获取输入的数据
    let name = document.querySelector('#goods-name').value
    let price = document.querySelector('#goods-price').value
    let num = document.querySelector('#goods-num').value
    let type = document.querySelector('#goods-type').value
    let desc = document.querySelector('#goods-desc').value
    let imgurl = document.querySelector('#imgurl').value

    if (!name || !price || !num || !type || !desc || !imgurl) {
        alert('输入内容不能为空')
        return
    }

    // 发送添加商品请求
    axios({
        method: 'post',
        url: 'http://localhost:8080/goods/add',
        data: {name,price,num,type,desc,imgurl}
    })
    .then((res)=>{
        alert(res.data.msg)
        if (res.data.code === 1) {
            document.querySelector('#goods-name').value = ''
            document.querySelector('#goods-price').value = ''
            document.querySelector('#goods-num').value = ''
            document.querySelector('#goods-type').value = ''
            document.querySelector('#goods-desc').value = ''
            document.querySelector('#imgurl').value = ''
        }
    })
}
